import re

from django.contrib.auth.hashers import make_password
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.mail import send_mail
from django.conf import settings

from app01.models import *
from .sers import UserModelSerializer


class RegisterView(APIView):
    """
    用户注册:需要提供以下数据
        用户名、密码、确认密码、邮箱
    """
    def post(self, request):
        """
        {'username':['zhangsan'],'password1:['123'],'password2':{"123"]}
        """
        username = request.data.get('username')
        password1 = request.data.get('password1')
        password2 = request.data.get('password2')
        email = request.data.get('email')

        # 判断数据完整
        if not all({username, password1, password2, email}):
            return Response({'msg': '数据不完整', 'code': 400})

        # 正则判断邮箱
        ex_email = re.compile(r'^.*@[a-zA-Z0-9]{2,3}.com')
        if not re.match(ex_email, email):
            return Response({'msg': '邮箱格式不正确', 'code': 400})

        # 判断用户是否存在
        user_obj = User.objects.filter(username=username).first()
        if user_obj:
            return Response({'msg': '用户已注册', 'code': 400})

        # 两次密码验证
        if password1 == password2:
            # 构造数据
            user_data = {'username': username, 'password': make_password(password1), 'email': email}
            user_serializer = UserModelSerializer(data=user_data)
            # 校验数据
            if user_serializer.is_valid():
                user_serializer.save()
                print(user_serializer.data)
                subject = '美多商城会员注册呀'
                message = ''
                from_email = settings.EMAIL_FROM
                recipient_list = [email]
                html_message = "{},欢迎注册美多商城会员，请点击以下链接激活:<br />" \
"<a href='http://127.0.0.1:8000/app01/active/?user_id={}'>激活会员请点击</a>".format(username, user_serializer.data.get('id'))
                send_mail(subject, message, from_email, recipient_list,
                          html_message=html_message)
                return Response({'msg': '注册成功', 'code': 200})
            else:
                return Response({'error': user_serializer.errors, 'code': 400})

        else:
            return Response({'msg': '两次密码不一致', 'code': 400})


class CheckUsername(APIView):

    def get(self,request):
        username = request.query_params.get('username')
        user_obj = User.objects.filter(username=username)
        if user_obj:
            return Response({'msg': '用户已存在', 'code':400})
        else:
            return Response({'msg': 'OK', 'code': 200})


class ActiveView(APIView):

    def get(self, request):
        user_id = request.query_params.get('user_id')
        return Response({'msg': 'OK'})

